package com.ecoolex.chinadutyfree.retailer.core.manager;

import java.time.Instant;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ecoolex.chinadutyfree.retailer.core.dao.UserExternalInfoDAO;
import com.ecoolex.chinadutyfree.retailer.entity.UserExternalInfo;
import com.ecoolex.chinadutyfree.retailer.entity.UserExternalInfoExample;
import com.ecoolex.chinadutyfree.retailer.entity.UserExternalInfoExample.Criteria;

@Service
public class UserExternalInfoManager {
	
    @Autowired
    private UserExternalInfoDAO dao;
    
    public Boolean existByExternalUserId(String externalUserId) {
		UserExternalInfoExample example = new UserExternalInfoExample();
		Criteria criteria = example.createCriteria();
		criteria.andExternalUserIdEqualTo(externalUserId).andDeletedEqualTo(UserExternalInfo.NOT_DELETED);
    	return dao.countByExample(example) > 0;
	}

	public UserExternalInfo getByExternalUserId(String externalUserId) {
		UserExternalInfoExample example = new UserExternalInfoExample();
		Criteria criteria = example.createCriteria();
		criteria.andExternalUserIdEqualTo(externalUserId).andDeletedEqualTo(UserExternalInfo.NOT_DELETED);;
		return dao.selectOneByExample(example);
	}

	public UserExternalInfo addUserExternalInfo(Integer userId, String externalUserId, String createUser) {
		UserExternalInfo userExternalInfo = new UserExternalInfo();
		userExternalInfo.setUserId(userId);
		userExternalInfo.setExternalUserId(externalUserId);
		userExternalInfo.setDeleted(UserExternalInfo.NOT_DELETED);
		userExternalInfo.setCreateUser(createUser);
		userExternalInfo.setCreateTime(Date.from(Instant.now()));
		userExternalInfo.setUpdateUser(createUser);
		userExternalInfo.setUpdateTime(Date.from(Instant.now()));
		dao.insert(userExternalInfo);
		return userExternalInfo;
	}

	public UserExternalInfo getByUserId(Integer userId) {
		UserExternalInfoExample example = new UserExternalInfoExample();
		Criteria criteria = example.createCriteria();
		criteria.andUserIdEqualTo(userId).andDeletedEqualTo(UserExternalInfo.NOT_DELETED);;
		return dao.selectOneByExample(example);
	}
}